package br.ufmg.ubicomp.droidguide.communication;

import java.util.Map;

import br.ufmg.ubicomp.droidguide.common.EntityProperties;
import br.ufmg.ubicomp.droidguide.eventservice.DroidGuideRemoteService;

public class CommunicationManager {

	private CommNotificationListener listener;
	
	public void execute(DGCommManagerOperation operation, 
			Map<String, String> params, CommNotificationListener listener) throws Exception
	{
		this.listener = listener;
		CommThread ct = new CommThread(params, operation, this);
		ct.start();
	}
	
	public CommNotificationListener getListener() {
		return listener;
	}
	
	private class CommThread extends Thread{
		private Map<String, String> params;
		private DGCommManagerOperation operation;
		private Object returnValue = null;
		private CommunicationManager manager;

		public CommThread(Map<String, String> params, DGCommManagerOperation operation, 
				CommunicationManager manager) {
			super();
			this.params = params;
			this.operation = operation;
			this.manager = manager;
		}
		
		@Override
		public void run(){
			DroidServiceParamCommService service = new DroidServiceParamCommService();
			String key = null;
			switch (operation)
			{
			case SAVE_SERVICE_PARAM_VALUE:
				key = params.get("key");
				String value = params.get("value");
				EntityProperties entity = null;
					try {
						entity = service.saveServiceParamValue(key, value);
					} catch (Exception e) {
						throwRuntimeException(e);
					}
				returnValue = entity;
				break;
			case GET_SERVICE:
				key = params.get("key");
				String dgkey = params.get("droidGuideUserKey");
				DroidGuideRemoteService remService = null;
				try {
						remService = service.getService(key, dgkey);
					} catch (Exception e) {
						throwRuntimeException(e);
					}
				returnValue = remService;
				break;
			}
			manager.getListener().notifyIncommingMessage(operation, returnValue);
		}

		private void throwRuntimeException(Exception e) {
			e.printStackTrace();
			RuntimeException re = new RuntimeException();
			re.setStackTrace(e.getStackTrace());
			throw re;
		}
		
	}
	
}
